import java.util.concurrent.Semaphore;
import java.util.function.IntConsumer;

/**
 * 1116. 打印零与奇偶数
 * https://leetcode-cn.com/problems/print-zero-even-odd/
 */
public class Solutions_1116 {
    public static void main(String[] args) {
//        int n = 5;  // output: "0102030405"
        int n = 2;  // output: "0102"

        ZeroEvenOdd obj = new ZeroEvenOdd(n);
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    obj.zero(System.out::print);
                } catch(InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    obj.odd(System.out::print);
                } catch(InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    obj.even(System.out::print);
                } catch(InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t3.start();
        t2.start();
        t1.start();
    }
}

/**
 * 解题思路：信号量
 */
class ZeroEvenOdd {
    private int n;
    private Semaphore zero;
    private Semaphore odd;
    private Semaphore even;

    public ZeroEvenOdd(int n) {
        this.n = n;
        // 关键：zero 先执行，故初始信号量为 1
        zero = new Semaphore(1);
        // 其他线程信号量为 0
        odd = new Semaphore(0);
        even = new Semaphore(0);
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            zero.acquire();
            printNumber.accept(0);
            // 打印偶数时，释放 even 信号量，否则释放 odd 信号量
            if (i % 2 == 0) {
                even.release();
            } else {
                odd.release();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for (int i = 2; i <= n; i += 2) {
            // 获取信号量，没有时线程阻塞
            even.acquire();
            printNumber.accept(i);
            // 释放 zero 信号量，让线程 1 执行
            zero.release();
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i += 2) {
            // 获取信号量，没有时线程阻塞
            odd.acquire();
            printNumber.accept(i);
            // 释放 zero 信号量，让线程 1 执行
            zero.release();
        }
    }
}